package com.iss.springdemo1.mvc.controller;

import com.iss.springdemo1.mvc.model.ResponseMessage;
import com.iss.springdemo1.mvc.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RequestMapping("stock")
// @Controller @ResponseBody
public class StockController {

  /*  @Autowired
    private HttpServletRequest request;  属性注入
*/
     /*对HttpServletRequest来说，
     * 实现方法注入*/
    @RequestMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file,
                         HttpServletRequest request){
        /**
         *  1. 创建文件
         *  2. 保存到服务端的物理磁盘
        * */
        String fileName = file.getOriginalFilename();

        String path = request.getSession().getServletContext().getRealPath("/upload");

        /*方法1：*/

          File serverFile = new File(path,fileName);
        if(!serverFile.getParentFile().exists()){
            serverFile.getParentFile().mkdirs();
        }

        try {
            file.transferTo(serverFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return  path;
    }


    @RequestMapping("/download")
    public void download(String filename,HttpServletResponse response) throws IOException {
        System.out.println("fileName:"+filename);

       String path = "E://upload";
       File file=new File(path,filename);
       FileInputStream fis = new FileInputStream(file);
        response.setHeader("Content-disposition","attachment;fileName="+filename);
        ServletOutputStream os = response.getOutputStream();
        byte []  buff=new byte[1024];
        int len=0;

        while ((len=fis.read(buff))>0){
            os.write(buff,0,len);
        }

        fis.close();

    }

}
